from . import news_blue
from flask import render_template, current_app, jsonify, abort, session, request, g

from ... import db
from ...commons import user_login_data
from ...models import News, User, Comment, CommentLike
from ...utils.response_code import RET

# 功能描述：关注&取消关注
@news_blue.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():
    # 判断用户是否有登陆
    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg="用户未登录")
    # 获取参数
    author_id = request.json.get('user_id')
    action = request.json.get("action")
    # 校验参数，为空校验
    if not all([author_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # 判断操作类型
    if action not in ("follow","unfollow"):
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")
    # 根据作者编号取出作者对象，判断作者对象是否存在
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")
    if not author:
        return jsonify(errno=RET.NODATA,errmsg="作者不存在")

    try:
        # 关注或取消关注
        if action == "follow":
            if not g.user in author.followers:
                author.followers.append(g.user)
        # 返回响应
        else:
            if g.user in author.followers:
                author.followers.remove(g.user)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="操作失败")
    # 返回响应
    return jsonify(errno=RET.OK,errmsg="操作成功")


# 功能描述：点赞&取消点赞
@news_blue.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    # - 判断用户是否登陆
    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg="用户没有登陆")
    # - 获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    # - 校验参数，为空校验
    if not all([comment_id,action]):
        return jsonify(errno=RET.NODATA,errmsg="参数不全")
    # - 操作类型校验
    if not action in ["add","remove"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")
    # - 根据评论编号获取评论对象, 判断是否存在
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取评论对象失败")
    if not comment: return jsonify(errno=RET.NODATA, errmsg="评论不存在")

    # - 根据操作类型点赞或者取消点赞
    try:
        if action == "add":
            # 判断当前用户是否对该评论点过赞
            comment_like = CommentLike.query.filter(CommentLike.user_id==g.user.id,CommentLike.comment_id==comment_id).first()
            if not comment_like:
                # 创建点赞对象
                comment_like = CommentLike()
                comment_like.user_id = g.user.id
                comment_like.comment_id = comment_id
                # 将对象添加到数据库
                db.session.add(comment_like)

                # 将评论的点赞数量+1
                comment.like_count+=1
                db.session.commit()

        else:
            comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                       CommentLike.comment_id == comment_id).first()
            if comment_like:
                # 将移除点赞对象
                db.session.delete(comment_like)

                # 将评论的点赞数量-1
                if comment.like_count > 0:
                    comment.like_count -= 1
                db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="点赞失败")
    # - 返回响应
    return jsonify(errno=RET.OK,errmsg="操作成功")

# 功能描述：评论&回复评论
@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    # 判断用户是否登陆
    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg="用户未登录")
    # - 获取参数
    news_id = request.json.get("news_id")
    content = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    # - 校验参数, 为空校验
    if not all([news_id,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # - 创建评论对象, 设置属性
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = content

    # - 判断是否有父评论编号
    if parent_id:
        comment.parent_id = parent_id
    # - 将评论添加到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(RET.DBERR,errmsg="评论失败")
    # - 返回响应, 携带评论数据
    return jsonify(errno=RET.OK,errmsg="评论成功",data=comment.to_dict())

# 功能描述：收藏&取消收藏
@news_blue.route('/news_collect',methods=['POST'])
@user_login_data
def news_collect():
    # 判断用户是否登陆
    # 判断用户登录状态
    # user_id = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg="该用户未登陆")

    # if not g.user:
    #     return jsonify(errno=RET.NODATA,errmsg="用户未登陆")
    # - 获取参数
    news_id=request.json.get('news_id')
    action = request.json.get('action')
    # - 校验参数, 为空校验
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # - 判断操作类型(收藏或者取消收藏)
    if not action in ["collect","cancel_collect"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")
    # - 通过新闻编号取出新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.loggere.error(e)
        return jsonify(errno=RET.DBERR,errmsg="新闻获取失败")
    # - 判断新闻对象是否存在
    if not news:
        return jsonify(errno=RET.NODATA,errmsg="新闻不存在")

    try:
        # - 根据操作类型收藏或取消收藏
        if action == "collect":
            # 判断用户是否已经对该新闻收藏过了
            if not news in g.user.collection_news:
                g.user.collection_news.append(news)
        else:
            if news in g.user.collection_news:
                g.user.collection_news.remove(news)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="操作失败")
    return jsonify(errno=RET.OK,errmsg="操作成功")

    # - 返回响应

@news_blue.route('/<int:news_id>')
@user_login_data
def new_index(news_id):
    # # 获取用户id
    # user_id = session.get("user_id")
    # # 获取用户登陆数据
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)


    # 根据新闻编号找出新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻对象失败")

    # 判断news对象是否存在
    if not news:
        abort(404)

    # 查询热门新闻的前5条数据
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(5).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    # 新闻列表转为字典列表
    click_news_list = []
    for click_news in news_list:
        click_news_list.append(click_news.to_dict())

    # 处理登陆用户是否对该新闻收藏过
    is_collected = False
    if g.user and news in g.user.collection_news:
        is_collected = True

    # 查询该新闻的所有评论内容
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(RET.DBERR,errmsg="获取评论内容失败")

    like_comment_ids = []
    if g.user:
        # 获取用户的所有点赞
        try:
            comment_likes = CommentLike.query.filter(CommentLike.user_id==g.user.id).all()
        except Exception as e:
            current_app.logger.error(e)

        # 遍历获取用户点赞过的评论编号

        for comment_like in comment_likes:
            like_comment_ids.append(comment_like.comment_id)

    # 将评论对象列表转为评论字典列表
    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        # 假设用户对所有评论都没点过赞
        comment_dict["is_like"] = False
        # if 用户需要登陆 and 评论的编号在用户点赞过的评论编号里
        if g.user and comment.id in like_comment_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)

    # 判断该用户是否关注过该新闻的作者
    is_followed = False
    if g.user and news.user:
        if g.user in news.user.followers:
            is_followed = True


    # 携带新闻数据，渲染页面
    data = {
        "news_info":news.to_dict(),
        "user_info":g.user.to_dict() if g.user else "",
        "click_news_list":click_news_list,
        "is_collected":is_collected,
        "comments":comment_list,
        "is_followed":is_followed
    }
    return render_template("news/detail.html",data=data)